package cn.it58.gooditname.actions

import cn.it58.gooditname.services.ConfigService
import cn.it58.gooditname.services.NamingFormat
import cn.it58.gooditname.services.TranslationService
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.SelectionModel
import com.intellij.openapi.options.ShowSettingsUtil
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages

/**
 * 基础转换动作类
 */
abstract class BaseConvertAction : AnAction() {

    companion object {
        private const val NOTIFICATION_GROUP_ID = "GoodName Notifications"
    }

    /**
     * 获取命名格式
     */
    protected abstract fun getNamingFormat(): NamingFormat

    /**
     * 获取格式名称（用于显示）
     */
    protected abstract fun getFormatName(): String

    override fun actionPerformed(e: AnActionEvent) {
        val editor = e.getData(CommonDataKeys.EDITOR)
        val project = e.project

        if (editor == null || project == null) {
            return
        }

        val selectionModel = editor.selectionModel
        val selectedText = selectionModel.selectedText

        if (selectedText.isNullOrBlank()) {
            showNotification(
                project,
                "请先选中要转换的中文文本",
                NotificationType.WARNING
            )
            return
        }

        val configService = ConfigService.getInstance()
        
        // 检查配置
        if (!configService.isApiKeyConfigured() && configService.isApiEnabled()) {
            showConfigurationPrompt(project)
            return
        }

        // 在后台任务中执行翻译
        ProgressManager.getInstance().run(object : Task.Backgroundable(project, "正在翻译中...", true) {
            override fun run(indicator: ProgressIndicator) {
                indicator.text = "正在翻译「${selectedText.trim()}」为${getFormatName()}格式..."
                
                try {
                    val translationService = TranslationService.getInstance()
                    val result = translationService.translate(selectedText.trim(), getNamingFormat())

                    ApplicationManager.getApplication().invokeLater {
                        if (result.isNotBlank()) {
                            // 替换选中的文本
                            WriteCommandAction.runWriteCommandAction(project) {
                                editor.document.replaceString(
                                    selectionModel.selectionStart,
                                    selectionModel.selectionEnd,
                                    result
                                )
                            }

                            // 显示成功通知
                            showNotification(
                                project,
                                "✅ 转换成功：「$selectedText」→「$result」(${getFormatName()})",
                                NotificationType.INFORMATION
                            )
                        } else {
                            showNotification(
                                project,
                                "❌ 翻译失败，请检查网络连接或API配置",
                                NotificationType.ERROR
                            )
                        }
                    }
                } catch (ex: Exception) {
                    ApplicationManager.getApplication().invokeLater {
                        showNotification(
                            project,
                            "❌ 转换过程中发生错误: ${ex.message}",
                            NotificationType.ERROR
                        )
                    }
                }
            }
        })
    }

    /**
     * 显示配置提示
     */
    private fun showConfigurationPrompt(project: Project) {
        val result = Messages.showYesNoDialog(
            project,
            "检测到您还未配置API密钥。\n\n" +
                    "• 配置API密钥后可使用AI智能翻译\n" +
                    "• 不配置也可使用本地词典翻译\n\n" +
                    "是否现在去配置？",
            "GoodName - 配置提示",
            "立即配置",
            "使用本地翻译",
            Messages.getQuestionIcon()
        )

        if (result == Messages.YES) {
            // 跳转到配置页面
            ShowSettingsUtil.getInstance().showSettingsDialog(project, "GoodName")
        } else {
            // 关闭API功能，使用本地翻译
            val configService = ConfigService.getInstance()
            configService.setApiEnabled(false)
            showNotification(
                project,
                "已切换到本地词典翻译模式，您可以随时在设置中启用AI翻译",
                NotificationType.INFORMATION
            )
        }
    }

    /**
     * 显示通知
     */
    private fun showNotification(project: Project, content: String, type: NotificationType) {
        val notificationGroup = NotificationGroupManager.getInstance()
            .getNotificationGroup(NOTIFICATION_GROUP_ID)
        
        notificationGroup.createNotification(content, type)
            .notify(project)
    }

    override fun update(e: AnActionEvent) {
        val editor = e.getData(CommonDataKeys.EDITOR)
        e.presentation.isEnabled = editor != null
    }
} 